package com.ims.word;

import com.ims.bookmark.BookMark;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;

import java.io.*;
import java.util.List;

/**
 * 读取word
 * @author gaoxu
 * @date 2019-07-04 17:31
 */
public class X02ReadWord {

    public static void main(String[] args) {

        try {
            /**
             * 97-2007
             */
           /* // 创建新的工作簿
            Workbook wb = new HSSFWorkbook();
            // 创建新的Sheet页
            Sheet sheet1 = wb.createSheet("第一个Sheet页");
            Sheet sheet2 = wb.createSheet("第二个Sheet页");
            // 在指定位置写入工作簿
            OutputStream fileOut = new FileOutputStream("hellExcel97-2007.xls");
            wb.write(fileOut);
            fileOut.close();*/

            /**
             * 2007
             */
            //读取word文件
            String reportWord = "F:\\技术成熟度技术评估报告模板.docx";
            File file = new File(reportWord);
            InputStream in = new FileInputStream(file);
            XWPFDocument doc = new XWPFDocument(in);

            //段落
           /* XWPFParagraph paragraph = doc.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText("Java POI 生成word文件。");
            run.setColor("696969");
            run.setFontSize(16);*/

            //读取段落中的书签
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            for (XWPFParagraph paragraph : paragraphList) {
                List<CTBookmark>  bookmarkList = paragraph.getCTP().getBookmarkStartList();
                for (CTBookmark bookmark : bookmarkList) {
                    System.out.println(bookmark.getName());;
                }
            }
           /* XWPFRun run = this._para.createRun();
            run.setText("xx");*/

            //读取表格中的书签
            List<XWPFTable> tableList = doc.getTables();
            for (XWPFTable table : tableList) {
                List<XWPFTableRow> rowList = table.getRows();//得到表格的行
                for (XWPFTableRow row : rowList) {
                    List<XWPFTableCell> cellList = row.getTableCells();//得到行中的单元格
                    for (XWPFTableCell cell : cellList) {
                        List<XWPFParagraph> paragraphList2 = cell.getParagraphs();  //行中的段落
                        for (XWPFParagraph paragraph : paragraphList2) {
                            List<CTBookmark> bookmarkList = paragraph.getCTP().getBookmarkStartList();
                            for (CTBookmark bookmark : bookmarkList) {
                                System.out.println(bookmark.getName());;
                            }
                        }
                    }
                }
            }

            //输出doc
            OutputStream fileOut = new FileOutputStream("hellExcel2-2007.docx");
            doc.write(fileOut);
            fileOut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
